<template>
  <div class="article-container">
    <!-- 卡片区域 -->
    <el-card class="filter-card">
      <div slot="header" class="clearfix">
        <my-breadcrumb></my-breadcrumb>
      </div>
      <!-- 表单区域 -->
      <el-form label-width="80px">
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <!-- 如果选择了全部，则status的值为null，axios不会发送该参数 -->
            <el-radio :label="null">全部</el-radio>
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">待审核</el-radio>
            <el-radio :label="2">审核通过</el-radio>
            <el-radio :label="3">审核失败</el-radio>
            <el-radio :label="4">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 在子组件上使用v-model指令，会自动给子组件添加input事件监听，此时需要在子组件内部抛出input事件 -->
        <my-channel v-model="form.channelId"></my-channel>
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="hSearch" :loading="isLoading"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        根据筛选条件共查询到 {{ total_count }} 条结果：
      </div>
      <!-- 数据列表 -->
      <el-table
        :data="articles"
        stripe
        style="width: 100%"
        class="list-table"
        size="mini"
        v-loading="isLoading"
      >
        <el-table-column label="封面" width="180">
          <template slot-scope="scope">
            <el-image
              style="width: 150px; height: 100px"
              :src="scope.row.cover.images[0]"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="180">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | fStatusType">{{
              scope.row.status | fStatusText
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pubdate" label="发布时间"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="hEdit(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="hDelete(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- /数据列表 -->

      <!-- 列表分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="10"
        @current-change="hPageChange"
        :total="total_count"
        :disabled="isLoading"
      >
      </el-pagination>
      <!-- /列表分页 -->
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'articles',
  data () {
    return {
      isLoading: false,
      articles: [],
      total_count: 0,
      page: 1,
      form: {
        channelId: null,
        status: null, // 文章状态
        dateRange: null // 时间区间,如果有值，就是一个数组
      }
    };
  },
  // 过滤器，用于转换文章状态
  filters: {
    fStatusType (status) {
      // 策略模式 --- 设计模式（套路）
      const types = {
        0: 'info',
        1: 'normal',
        2: 'success',
        3: 'warning',
        4: 'danger'
      };
      return types[status];
    },
    fStatusText (status) {
      const texts = {
        0: '草稿',
        1: '待审核',
        2: '审核通过',
        3: '审核失败',
        4: '已删除'
      };
      return texts[status];
    }
  },
  methods: {
    buildParams () {
      const { dateRange, status, channelId } = this.form;
      const params = {
        page: this.page,
        status,
        channel_id: channelId
      };
      if (dateRange) {
        params.begin_pubdate = dateRange[0];
        params.end_pubdate = dateRange[1];
      }
      return params;
    },
    async getArticleList () {
      this.isLoading = true;
      const params = this.buildParams();
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/articles',
          method: 'GET',
          params
        });
        this.articles = res.data.data.results;
        this.total_count = res.data.data.total_count;
      } catch (err) {
        console.log(err);
        this.articles = [];
      }
      this.isLoading = false;
    },
    hEdit (row) {
      const id = row.id.toString()
      this.$router.push('/edit/' + id)
    },
    hDelete (row) {
      // console.log(row)
      this.$confirm('确认删除该篇文章吗？').then(() => {
        // 若id是大整数，被处理后是一个对象，需要toString方法转成字符串
        const id = row.id.toString()
        this.doDelete(id)
      }).catch(() => {
        console.log('取消了删除~~~')
      })
    },
    async doDelete (id) {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/articles/' + id,
          method: 'DELETE'
        })
        console.log(res);
        this.$message.success('删除成功~~~')
        // 重新请求数据
        this.getArticleList()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败~~~');
      }
    },
    hPageChange (curPage) {
      console.log('点击了分页', curPage);
      // 更新页码
      this.page = curPage;
      //   重新请求数据
      this.getArticleList();
    },
    hSearch () {
      this.getArticleList();
    }
  },
  created () {
    this.getArticleList();
  }
};
</script>

<style lang="less" scoped>
.filter-card {
  margin-bottom: 30px;
}

.list-table {
  margin-bottom: 20px;
}
</style>
